# -*- coding: utf-8 -*-
import re
import urllib

def handleRequestURL(keys, request_url, dealwith='xml'):
    a = isinstance(request_url, unicode)
    if a:
        try:
            request_url = unicode(request_url, "utf-8")
        except:
            request_url = unicode(request_url, "gb2312")
#        raise "a is unicode:%s" % str(request_url)
    else:
        try:
            request_url = urllib.unquote(request_url.decode("utf-8").encode("utf-8"))
        except:
            pass
#            request_url = urllib.unquote(request_url.decode("gb2312").encode("gb2312"))
#        raise "a is not unicode:%s" % str(request_url)
#    raise str(request_url)
    if dealwith == 'xml':
        dict = {}
        dict.update({"size": [300, 500]})
        dict.update({"type": "line"})
        dict.update({"labels": []})
        dict.update({"alt": "#YValue"})
        dict.update({"title": ""})
        dict.update({"view3d": "false"})
        for key in keys:
            dict.update(handleParam(key, request_url))
        datas = dict["datas"]
        labels = dict["labels"]
        diff = datas.__len__() - labels.__len__()
        if diff > 0:
            for i in range(diff):
                labels.append(" ")
        
        for data_dict in datas:
            try:
                type = data_dict["type"]
            except KeyError:
                data_dict.update({"type": dict["type"]})
            data = data_dict["data_list"]
            data = zip(data, labels)
            data_dict["data_list"] = data
#            raise str(data)
#        raise str(datas)
#        datas = zip(datas, labels)
#        raise str(datas)
        dict.update({"datas": datas})
        return dict
    else:
        list = []
        for key in keys:
            result = handleParam(key, request_url, dealwith)
            if isinstance(result, unicode):
                result = result.decode("utf-8").encode("utf-8")
#                raise "result is unicode: %s" % str(result)
            else:
                try:
                    result = result.decode("utf-8").encode("utf-8")
                except:
                    result = result.decode("gb18030").encode("utf-8")
            
            list.append(result)
#        raise str(list)
#        list = [i.decode("utf-8").encode("gb2312") for i in list]
        result_url = "&".join(list)
        return result_url


def handleParam(key, request_url, dealwith='xml'):
#    raise str(a)
    request_list = request_url.split("&")
    dict = {}
    for req in request_list:
        try:
            dict[req.split("=")[0]] = req.split("=")[1]
        except IndexError:
            pass
    return {
        "datas":  lambda request_url, dealwith: handleDatas(dict[key], dealwith),
        "labels": lambda request_url, dealwith: handleLabels(dict[key], dealwith),
        "type":   lambda request_url, dealwith: handleType(dict[key], dealwith),
        "alt":    lambda request_url, dealwith: handleAlt(dict[key], dealwith),
        "size":   lambda request_url, dealwith: handleSize(dict[key], dealwith),
        "title":  lambda request_url, dealwith: handleTitle(dict[key], dealwith),
        "view3d": lambda request_url, dealwith: handleView3d(dict[key], dealwith)
    }[key](dict[key], dealwith)


def handleDatas(params, dealwith='xml'):
    params = urllib.unquote(params)
    
    if dealwith == 'xml':
#        pattern_combination = r"\w+:[\d+(.\d+)^|]+(\w+:[\d+(.\d+)^|]+)+"
        pattern_combination = r"\w+:[\d+(.\d+)^|]+"
        pattern_common      = r"[\d+(.\d+)^]+"
#        datas = re.compile(pattern_combination).search(params).group()
#        params = re.sub(r"[+]", "", params)
#        all_list = re.findall(r"\w+:[\d+(.\d+)^|]+", params)
#        data_list = []
#        for p in all_list:
#            type = p.split(":")[0]
#            datas = p.split(":")[1]
#            core_datas = datas.split("|")
#            for core_data in core_datas:
#                data = core_data.split("^")
#                dict = {}
#                dict.update({"type": type})
#                dict.update({"data_list": data})
#                data_list.append(dict)
#        raise str(data_list)
        try:
            datas = re.compile(pattern_combination).search(params).group()
            params = re.sub(r"[+]", "", params)
            all_list = re.findall(r"\w+:[\d+(.\d+)^|]+", params)
            data_list = []
            for p in all_list:
                type = p.split(":")[0]
                datas = p.split(":")[1]
                core_datas = datas.split("|")
                for core_data in core_datas:
                    data = core_data.split("^")
                    dict = {}
                    dict.update({"type": type})
                    dict.update({"data_list": data})
                    data_list.append(dict)
        except:
            datas = re.compile(pattern_common).search(params).group()
            datas = datas.split("^")
            dict = {"data_list": datas}
            data_list = []
            data_list.append(dict)
            return {"datas": data_list}
        return {"datas": data_list}
    else:
        pattern_combination = r"\w+:[\d+(.\d+),|]+(\w+:[\d+(.\d+),|]+)+"
        pattern_common      = r"[\d+(.\d+),]+"
        p_combination = re.compile(pattern_combination)
        p_common      = re.compile(pattern_common)
#        test
#        url_datas = p_combination.search(params).group()
#        url_datas = re.sub(",", "^", url_datas)
##        url_datas = re.sub("+", "^", url_datas)
#        params = re.sub(pattern_combination, url_datas, params)
#        
#        raise ("%s\n%s" % (str(params), str(url_datas)))
        
        try:
            url_datas = p_combination.search(params).group()
            url_datas = re.sub(",", "^", url_datas)
#            url_datas = re.sub("+", "^", url_datas)
            params = re.sub(pattern_combination, url_datas, params)
        except:
            url_datas = p_common.search(params).group()
            url_datas = re.sub(",", "^", url_datas)
            params = re.sub(pattern_common, url_datas, params)
            return "datas=%s" % params
#        except:
#            return "datas="
        return "datas=%s" % params


def handleLabels(params, dealwith='xml'):
    params = urllib.unquote(params)
    if dealwith == 'xml':
        patterns = ".*"
        p = re.compile(patterns)
        labels = p.search(params).group()
        labels = labels.split("|")
        return {"labels": labels}
    else:
        patterns_labels = ".*"
        p_labels = re.compile(patterns_labels)
        try:
            url_labels = p_labels.search(params).group()
            url_labels = re.sub(",", "|", url_labels)
            url_labels = re.sub(":", "|", url_labels)
            params = re.sub(patterns_labels, url_labels, params)
        except:
            return "labels="
        return "labels=%s" % params


def handleType(params, dealwith='xml'):
#    try:
#        params = urllib.unquote(params).decode('gb2312')
#    except:
#        params = urllib.unquote(params).decode('utf-8')
#    else:
#        params = urllib.unquote(params)
#    url_type = re.compile("type=[\S:]+").search(request_url).group()
    type = re.compile("[\\w]+").search(params).group()
    if dealwith == 'xml':
        return {"type": type}
    else:
        return "type=%s" % type


def handleAlt(params, dealwith='xml'):
    params = urllib.unquote(params)
    if dealwith == 'xml':
    #    alt = re.compile("[\\S+]+").search(params).group()
        params = re.sub("\[x\]", "#AxisXLabel", params)
        params = re.sub("\[y\]", "#YValue", params)
        params = re.sub("\[X\]", "#AxisXLabel", params)
        params = re.sub("\[Y\]", "#YValue", params)
        
        params = urllib.unquote(params)#.decode('gb2312')
        return {"alt": params}
    else:
        patterns_alt = ".*"
        p_alt = re.compile(patterns_alt)
        substr = '，'
    #    substr = urllib.unquote(substr).decode('utf-8')
        try:
            url_alt = p_alt.search(params).group()
            url_alt = re.sub(",", substr, url_alt)
            params = re.sub(patterns_alt, url_alt, params)
        except:
            return "alt="
        return "alt=%s" % params


def handleSize(params, dealwith='xml'):
    patterns = "(\d{1,3})x(\d{1,3})"
    p = re.compile(patterns)
    if dealwith == 'xml':
        try:
            size = p.search(params).group()
            size = size.split("x")
        except:
            return ""
        return {"size": size}
    else:
        try:
            size = p.search(params).group()
        except:
            return ""
        return "size=%s" % size


def handleTitle(params, dealwith='xml'):
    params = urllib.unquote(params)
#    raise params
    patterns = ".*"
    p = re.compile(patterns)
    if dealwith == 'xml':
        try:
            title = p.search(params).group()
        except:
            return {"title": "chart title"}
#        title = urllib.unquote(title).decode('utf-8').encode("utf-8")
        return {"title": title}
    else:
#        try:
#            params = params.decode("utf-8")
#        except:
#            params = params.decode("gb18030")
#        raise str(params.encode("utf-8"))
        try:
            title = p.search(params).group()
        except:
            return ""
        return "title=%s" % title


def handleView3d(params, dealwith='xml'):
    patterns = "true|false"
    p = re.compile(patterns)
    if dealwith == 'xml':
        try:
            view3d = p.search(params).group()
        except:
            return {"view3d": "false"}
        return {"view3d": view3d}
    else:
        try:
            view3d = p.search(params).group()
        except:
            return "view3d=false"
        return "view3d=%s" % view3d


def handlerNone(params, dealwith='xml'):
    return {"datas": [], "type": "line", "alt": "#YValue"}
